package com.fwj.auth.config;

import com.fwj.auth.entity.user.UserExtendAccount;
import com.fwj.core.common.common.CommonUtils;
import com.fwj.core.common.execption.CommonException;
import com.fwj.core.common.model.ResponseEnum;
import com.fwj.auth.api.user.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @Author: fwj
 * @Data: 2022/2/20 22:29
 * @Version 1.0
 * @Description:
 */

@Component
public class AuthUserService implements UserDetailsService {

    @Autowired
    private UserService userService;

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        try {
            if (CommonUtils.isEmpty(s)){
                throw new CommonException(ResponseEnum.MISS_PARAMETER);
            }
            List<UserExtendAccount> userExtendAccounts;
            //搜索账号
            userExtendAccounts = userService.getLoginInfo(s);
            if (userExtendAccounts.size() > 1){
                throw new CommonException(ResponseEnum.USER_NO_EXISTS);
            }
            //返回账号信息进行匹配
            UserExtendAccount userExtendAccount = userExtendAccounts.get(0);
            return User.withUsername(userExtendAccount.getValue()).password(userExtendAccount.getPassword()).roles("admin", "user").build();
        } catch (Exception e){
            throw new CommonException(ResponseEnum.SERVER_ERROR);
        }
    }

}
